﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using FileTaggerData.Domain;
using NHibernate;
using FileTaggerData.Helpers;

namespace FileTags
{
    public partial class TagEditForm : Form
    {
        public TagEditForm()
        {
            InitializeComponent();
        }

        public FileTag Tag { get; set; }

        private void TagEditForm_Load(object sender, EventArgs e)
        {
            if (Tag == null)
            {
                MessageBox.Show(this, "Tag is not selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                DialogResult = System.Windows.Forms.DialogResult.None;
                this.Close();
            }
            else
            {
                txtTagName.Text = Tag.Name;
                txtTagDescription.Text = Tag.Description;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {

            if (string.IsNullOrWhiteSpace(txtTagName.Text) || string.IsNullOrEmpty(txtTagName.Text))
            {
                MessageBox.Show(this, "Tag Name is required parameter", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            
            using (ISession session = FactoryHolder.GetSession())
            {
                ITransaction trans = session.BeginTransaction();
                try
                {
                    session.Refresh(Tag);
                    Tag.Name = txtTagName.Text;
                    Tag.Description = txtTagDescription.Text == string.Empty ? null : txtTagDescription.Text;

                    session.Update(Tag);
                    trans.Commit();
                    DialogResult = System.Windows.Forms.DialogResult.OK;
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }


    }
}
